<script>
	import Vue from 'vue'
	const common = require('./static/js/common.js')
	export default {
		onLaunch: function(options) {
			/* 判断扫码进入的 */
			if (options && options.query && options.query.userId) this.globalData.sceneUpperId = options.query.userId
			if (options && options.query && options.query.goodId) this.globalData.sceneGoodId = options.query.goodId
			if (options && options.query && options.query.shopId) this.globalData.sceneShopId = options.query.shopId
			// this.updateManager()
			getCustom()
			console.log("onLaunch---options:", options);

			function getCustom() {
				let e = uni.getSystemInfoSync()
				// #ifndef MP
				Vue.prototype.StatusBar = e.statusBarHeight
				if (e.platform == 'android') {
					Vue.prototype.CustomBar = e.statusBarHeight + 50
				} else {
					Vue.prototype.CustomBar = e.statusBarHeight + 45
				}
				// #endif

				// #ifdef MP-WEIXIN || MP-QQ
				Vue.prototype.StatusBar = e.statusBarHeight
				let capsule = uni.getMenuButtonBoundingClientRect()
				if (capsule) {
					Vue.prototype.Custom = capsule
					// Vue.prototype.capsuleSafe = uni.upx2px(750) - capsule.left + uni.upx2px(750) - capsule.right;
					Vue.prototype.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight
				} else {
					Vue.prototype.CustomBar = e.statusBarHeight + 50
				}
				// #endif

				// #ifdef MP-ALIPAY
				Vue.prototype.StatusBar = e.statusBarHeight
				Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight
				// #endif
			}

			// 登录
			uni.login({
				success: res => {
					// 发送 res.code 到后台换取 openId, sessionKey, unionId
					console.log(46, res)
					this.postFormData('addons/shopro/user/wxMiniProgramLogin', {
							code: res.code
						})
						.then(res => {
							// this.getKEFU()
							uni.hideLoading()
							this.globalData.token = res.data.data.token
							this.getUser().then(data => {
								console.log('用户登录信息-->', res, data)
								this.globalData.user = data.data.data
								// 回调函数
								if (this.globalData.loginCallback) this.globalData.loginCallback()
							})
							
						})
						.catch(err => {
							console.log('67失败了-->', err)
						})
				}
			})

			// 获取用户信息
			uni.getSetting({
				success: res => {
					if (res.authSetting['scope.userInfo']) {
						// 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
						uni.getUserInfo({
							success: res => {
								// 可以将 res 发送给后台解码出 unionId
								this.globalData.userInfo = res.userInfo

								// 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
								// 所以此处加入 callback 以防止这种情况
								if (this.userInfoReadyCallback) {
									this.userInfoReadyCallback(res)
								}
							}
						})
					}
				}
			})
		},
		onShow() {
			uni.hideTabBar({
				animation: false
			})
		},
		methods: {
			// 新版本更新提醒
			updateManager() {
				const updateManager = uni.getUpdateManager()
				updateManager.onCheckForUpdate(function(res) {
					// 请求完新版本信息的回调
					console.log(res.hasUpdate)
				})
				updateManager.onUpdateReady(function(res) {
					uni.showModal({
						title: '更新提示',
						content: '新版本已经准备好，是否重启应用？',
						success(res) {
							if (res.confirm) {
								// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
								updateManager.applyUpdate()
							}
						}
					})
				})
				updateManager.onUpdateFailed(function(res) {
					// 新的版本下载失败
				})
			},
			// 判断登陆是否成功
			flagLogin() {
				return new Promise((resolve, reject) => {
					if (this.globalData.user) resolve()
					else {
						this.globalData.loginCallback = () => {
							resolve()
						}
					}
				})
			},
			// 获取用户信息
			async getUser() {
				return new Promise((resolve, reject) => {
					this.getData('addons/shopro/user/index', {}).then(res => {
						console.log('user', res)
						resolve(res)
					}).catch(err => {
						resolve()
					})
				})

			},
			// get
			getData(url, data) {
				return new Promise((resolve, reject) => {
					var that = this
					uni.request({
						url: that.globalData.IP + url,
						data: data,
						header: {
							token: that.globalData.token
						},
						success: res => {
							if (res.data.code == 1) resolve(res)
							else reject(res)
						},
						fail: err => {
							reject(err)
							console.log('发送数据失败')
						}
					})
				})
			},

			// post
			postData(url, data) {
				return new Promise((resolve, reject) => {
					var that = this
					uni.request({
						url: that.globalData.IP + url,
						data: data,
						header: {
							token: that.globalData.token,
							'content-type': 'multipart/form-data'
						},
						method: 'POST',
						success: res => {
							if (res.data.code == 1) resolve(res)
							else reject(res)
						},
						fail: err => {
							reject(err)
							console.log('发送数据失败')
						}
					})
				})
			},

			// formPost
			postFormData(url, data) {
				return new Promise((resolve, reject) => {
					var that = this
					uni.request({
						url: that.globalData.IP + url,
						data: data,
						method: 'POST',
						success: res => {
							if (res.data.code == 1) resolve(res)
							else reject(res)
						},
						fail: err => {
							reject(err)
							console.log('发送数据失败')
						}
					})
				})
			},

			// jsonPost
			postJsonData(url, data) {
				return new Promise((resolve, reject) => {
					var that = this
					uni.request({
						url: that.globalData.IP + url,
						data: JSON.stringify(data),
						method: 'POST',
						header: {
							'content-type': 'application/json',
							token: that.globalData.token
						},
						success: res => {
							if (res.data.code == 0) resolve(res)
							else reject(res)
						},
						fail: err => {
							reject(err)
							console.log('发送数据失败')
						}
					})
				})
			},

			// 图片上传
			uploadImg(file, pathName) {
				console.log('file => ', file, pathName)
				return new Promise((resolve, reject) => {
					var that = this
					uni.uploadFile({
						url: that.globalData.IP + 'util/singleUpload', //仅为示例，非真实的接口地址
						filePath: file,
						fileName: 'file',
						fileType: 'image',
						header: {
							token: that.globalData.token
						},
						formData: {
							path: pathName + '/'
						},
						success(res) {
							resolve(res)
						},
						fail(err) {
							reject(err)
							console.log('发送数据失败', err)
						}
					})
				})
			},

			/**
			 * 删除图片,多张
			 * @param {Array/String} imgs = [value]   图片地址
			 */
			deleteImgsFun(imgs) {
				return new Promise((reslove, reject) => {
					let urls = imgs
					if (imgs instanceof Array) urls = imgs.join(',')
					if (urls) {
						let param = {
							path: urls
						}
						this.getData('util/delFile', param, res => {
							if (res.data.code == 0) {
								reslove(res)
							} else {
								reject(res)
							}
						})
					}
				})
			},
			/* 复制 */
			setClipboardData(data) {
				uni.setClipboardData({
					data: data,
					success() {
						uni.showToast({
							title: '复制成功',
							duration: 1000
						})
					}
				})
			},
			//点击导航,导航到店家
			navigationShop(addr) {
				console.log('addr =》 ', addr);
				uni.openLocation({
					address: addr.addrDetail,
					name: addr.addr,
					latitude: addr.lat,
					longitude: addr.lng,
					fail: function(err) {
						uni.showToast({
							title: '打开地图失败'
						});
					}
				});
			},
			/**
			 * 订单处理计算逾期天数和违约金费用
			 * @param {Object} order
			 */
			dealOrderShow(order) {
				/* 计算逾期天数和违约金费用 */
				let overTimeDay = 0,
					overTimePrice = 0
				if (order.status == 5) {
					let nowStemp = new Date(new Date().toLocaleDateString()).getTime() //今天0点时间戳
					let orderEnd = order.orderKeepEnd || order.orderEnd
					if (nowStemp > orderEnd) {
						overTimeDay = parseInt((nowStemp - orderEnd) / 86400000) //逾期天数
						overTimePrice = parseInt(overTimeDay * order.penalAmount) //违约金费用
					}
				}
				order.overTimeDay = overTimeDay
				order.overTimePrice = overTimePrice
				return order
			},

			//  /* 获取是否隐藏个人入驻信息*/
			// 审核需要
			showDetail(Callback) {
				this.postFormData('extra/getListType', {
					type: 99
				}).then(res => {
					this.globalData.isShowDistriton = res.data.data[0].extraCon == 'false' ? false : true
					Callback()
				})
			},
			//定位
			getLocation(Callback) {
				let that = this;
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						that.globalData.latitude = res.latitude;
						that.globalData.longitude = res.longitude;
						Callback(res);
					}
				});
			},
		},
		globalData: {
			userInfo: null,
			user: null, // 用户信息
			imgUrl: 'https://gdw.wanwuhelian.com/',
			IP: 'https://gdw.wanwuhelian.com/',
			token: '',
			sceneUpperId: null, //扫码/链接进入的上级id
			sceneGoodId: null, //扫码/链接进入的商品id
			isShowDistriton: false, //是否显示分销
			loginCallback: null, //登录成功回调
			appId: '2021003141659008',
			latitude: 0, //坐标
			longitude: 0, //坐标
			phone: '', //客服电话
			reHide: false, //页面是否需要重载
			hideLoad: false,
			sceneShopId: null,
		}
	}
</script>

<style>
	/*每个页面公共css */
	@import '/static/wxss/common.css';

	page {
		--base: #3466ff;
		--baseSuccsess: #F4A13F;
		font-size: 26rpx;
		color: #333;
		padding-bottom: 120rpx;
	}
	
	image{
		width:100%;
		height: 100%;
	}

	.container {
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
		padding: 200rpx 0;
		box-sizing: border-box;
	}

	.flex {
		display: flex;
	}

	.justify {
		justify-content: space-between;
	}

	.justify_con {
		justify-content: center;
	}

	.align {
		align-items: center;
	}

	.wrap {
		flex-wrap: wrap;
	}

	.bg-main {
		background-color: var(--base);
	}

	.text-main {
		color: var(--base);
	}

	.line-base::after,
	.lines-base::after {
		border-color: var(--base);
	}

	.text-base,
	.line-base,
	.lines-base {
		color: var(--base);
	}

	.status_bar {
		height: var(--status-bar-height);
	}
</style>
